import * as step from '@flow-step/step-toolkit'
import dockerToolkit from '@flow-step/dockertoolkit'
import process from 'process'
import {getParams} from './params';
import {buildPushImage} from "./build-push";
import {dockerLogin} from "./login";

async function runStep(): Promise<void> {
    const params = getParams()
    step.info(`PIPELINE_ID=${params.pipelineID}`);
    step.info(`PIPELINE_NAME=${params.pipelineName}`);
    step.info(`BUILD_NUMBER=${params.buildNumber}`);
    step.info(`WORK_SPACE=${params.workSpace}`);
    step.info(`PROJECT_DIR=${params.projectDir}`);
    step.info(`BUILD_JOB_ID=${params.buildJobID}`)
    step.info(`STEP_ID=${params.stepID}`)
    step.info(`region=${params.region}`)
    step.info(`instance=${params.instance}`)
    step.info(`namespace=${params.namespace}`)
    step.info(`dockerRegistry=${params.dockerRegistry}`)
    step.info(`dockerTag=${params.dockerTag}`)
    step.info(`dockerfilePath=${params.dockerfilePath ?? ''}`)
    step.info(`contextPath=${params.contextPath ?? ''}`);
    step.info(`cacheType=${params.cacheType ?? ''}`)
    step.info(`cacheImageId=${params.cacheImageId ?? ''}`)
    step.info(`options=${params.options ?? ''}`)

    // check docker installation
    if (!dockerToolkit.checkDockerInstallation()) {
        process.exit(-1)
    }

    // check and wait docker daemon ready
    await dockerToolkit.waitDockerDaemonReady();
    // make sure docker buildx builder created
    dockerToolkit.createDockerBuildxBuilder()

    await dockerLogin(params.region, params.instance, params.useVpcAddress)
    await buildPushImage(params)
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
